package ufp2p;

import java.io.*;
import java.net.*;

public class ScreenWriter implements Runnable {

	Socket sock;
	String message;
	
	public ScreenWriter(Socket sock)
	{
		this.sock = sock;
	}
	
	public void run()
	{
		int current = 0;
        int bytesRead;
        byte[] mybytearray;
        

		
		
        try {
        	BufferedReader inFromServer2 =
    		        new BufferedReader(new InputStreamReader(sock.getInputStream()));
        	int partSize = Integer.parseInt(inFromServer2.readLine());
            mybytearray  = new byte [partSize];
            InputStream is = sock.getInputStream();
            FileOutputStream fos = new FileOutputStream("Hello.mp3");
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bytesRead = is.read(mybytearray,0,mybytearray.length);

            current = bytesRead;
            

            do {
               bytesRead =
                  is.read(mybytearray, current, (mybytearray.length-current));
				  
               if(bytesRead >= 0) {
                   //System.out.println("Length in if "+mybytearray.length);
                   current += bytesRead;
                   int value = current;
                   System.out.println(value);
               }

            } while(bytesRead > 0);
         
            bos.write(mybytearray, 0 , current);

            //System.out.println("a while");
            bos.flush();
            //long end = System.currentTimeMillis();
           // System.out.println(end-start);
            bos.close();
        
		while(true)
		{
			try{
		        message = inFromServer2.readLine();
		        System.out.println("FROM CLIENT: " + message);
		        
		        
			}
			catch(Exception e)
			{}
		}
        }catch(Exception e){}
	}
}
